const fs = require('fs');

const path = require('path');

const { articleTable, typeTable,commentTable } = require('../../schemas/index');

const { getResJson, formatTime } = require('../../assets/util');

const { HOST } = require('../../assets/config');

/**
 * 新增文章
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.addArticle = (params, callback) => {
    params.date = formatTime();
    params.compareDate = formatTime(new Date(),'YYYY-MM-DD');
    params.commentTotal = 0; // 评论次数默认 0
    params.readingTimes = 0; // 阅读次数默认 0
    params.likes = 0; // 点赞次数默认 0
    articleTable.insertMany(params, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data, '添加失败', false);
        } else {
            // 实现 type表中 articleTotal 自增
            typeTable.updateOne({ 'typeName': params.type }, { $inc: { articleTotal: 1 } }, err => {
                if (err) {
                    console.log('----------');
                    console.log(err);
                    console.log(`${params.type}-下属文章总数自增失败`);
                }
            });
            resJson = getResJson(data, '添加成功');
        }
        callback(resJson);
    })
}

/**
 * 删除文章
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.deleteArticle = (params, callback) => {
    // 拿到项目根目录
    const rootpath = path.join(__dirname, '../..');
    // 去查询该文章的详细信息做后续操作
    articleTable.findOne({ '_id': params._id }, (err, articleInfo) => {
        let coverImagesUrl = articleInfo.coverImagesUrl;
        let path = coverImagesUrl.replace(new RegExp(HOST, 'g'), rootpath);
        articleTable.deleteOne({ '_id': params._id }, (error, data) => {
            let resJson = {}
            if (error) {
                resJson = getResJson(data, '删除失败', false);
            } else {
                // 实现 type表中 articleTotal 自减
                typeTable.updateOne({ 'typeName': articleInfo.type }, { $inc: { articleTotal: -1 } }, err => {
                    if (err) {
                        console.log('----------');
                        console.log(err);
                        console.log(`${params.type}-下属文章总数自减失败`);
                    }
                });
                commentTable.deleteMany({articleId: params._id},err => {
                    if(err){
                        console.log('---------');
                        console.log(err);
                        console.log(`${articleInfo.title}-下属评论删除失败`);
                    }
                });
                // 删除掉该文章的封面图
                fs.unlinkSync(path);
                resJson = getResJson(data, '删除成功');
            }
            callback(resJson);
        })
    })
}

/**
 * 修改文章
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.editArticle = (params, callback) => {
    articleTable.updateOne({ '_id': params._id }, params, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data, '修改失败', false);
        } else {
            resJson = getResJson(data, '修改成功');
        }
        callback(resJson);
    })
}

/**
 * 查询文章
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.searchArticle = (params, callback) => {
    console.log(params);
    let searchJson = {
        compareDate: {
            $gte: params.startTime,
            $lte: params.endTime
        }
    }
    let count = articleTable.count(searchJson);
    count.exec((err, rs) => {
        articleTable.find(searchJson, (err, data) => {
            let resJson = {};
            if (err) {
                resJson = getResJson(data, '查询失败', false);
            } else {
                let paramsJson = {
                    list: data,
                    total: rs
                }
                resJson = getResJson(paramsJson, '查询成功');
            }
            callback(resJson);
        }).limit(params.pageSize).skip((params.pageNum - 1) * params.pageSize).sort({
            'compareDate': -1
        })
    })
}